/*
 * File     : StructureByValueParameter.java
 * Created  : 3 May 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import static com.googlecode.dni.internal.DniTypes.ALLOCATOR_TYPE;
import static com.googlecode.dni.internal.DniTypes.MEMORY_ACCESS_TYPE;
import static com.googlecode.dni.internal.DniTypes.POINTER_TYPE;
import static org.objectweb.asm.Opcodes.*;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import com.googlecode.dni.IllegalLibraryException;
import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.internal.DniTypes;
import com.googlecode.dni.internal.structure.StructureBuilder;
import com.googlecode.dni.internal.structure.StructureRecord;
import com.googlecode.dni.type.structure.Structure;

/**
 * <p>
 *  Encapsulates a parameter to a native call that holds a structure to be
 *  returned by value.  Used by the UNIX-style calling conventions. The same
 *  instance must be used both as a parameter and as the return type.
 * </p>
 *
 * @author Matthew Wilson
 */
final class ReturnStructureByValueParameter extends Parameter
{

    private final StructureRecord structureRecord;


    /**
     * @param parameter
     *            the structure by value parameter being replaced
     */
    ReturnStructureByValueParameter( final StructureByValueParameter parameter )
    {
        Class< ? extends Structure > structType = parameter.getJavaType().asSubclass( Structure.class );
        this.structureRecord = DniInternal.getStructureRecord( structType );

        if ( this.structureRecord.getInfo().getSize() <= 0 )
        {
            throw new IllegalLibraryException( "Cannot return opaque structure by value: " + structType.getName() );
        }

        setNativeTypeAsPointer();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    int getJavaVarSlots()
    {
        return 0;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    boolean needsScratchMemory()
    {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeScratchMemorySize( final MethodVisitor methodVisitor )
    {
        StructureBuilder.writeConstantInt( methodVisitor, this.structureRecord.getInfo().getSize() );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeGetParameter( final MethodVisitor methodVisitor )
    {
        writeGetScratchPointer();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    void writeReturnParameter( final MethodVisitor methodVisitor, final int returnVarIndex )
    {
        String factoryType = this.structureRecord.getFactory().getClass().getName().replace( '.', '/' );
        String implType = this.structureRecord.getImplType().getName().replace( '.', '/' );

        methodVisitor.visitFieldInsn( GETSTATIC,
                                      factoryType,
                                      "INSTANCE",
                                      "L" + factoryType + ";" );

        methodVisitor.visitFieldInsn( GETSTATIC,
                                      MEMORY_ACCESS_TYPE,
                                      "ALLOCATOR",
                                      "L" + ALLOCATOR_TYPE + ";" );
        
        methodVisitor.visitTypeInsn( NEW, POINTER_TYPE );
        methodVisitor.visitInsn( DUP );
        writeGetScratchPointer();
        if ( getNativeType() == 'I' )
        {
            methodVisitor.visitInsn( I2L );
        }
        methodVisitor.visitMethodInsn( INVOKESPECIAL,
                                       POINTER_TYPE,
                                       "<init>",
                                       "(J)V" );

        StructureBuilder.writeConstantInt( methodVisitor, this.structureRecord.getInfo().getSize() );
        methodVisitor.visitMethodInsn( INVOKEINTERFACE,
                                       ALLOCATOR_TYPE,
                                       "copy",
                                       "(L" + POINTER_TYPE + ";I)L" + POINTER_TYPE + ";" );

        methodVisitor.visitMethodInsn( INVOKEVIRTUAL,
                                       factoryType,
                                       "fromPointer",
                                       "(L" + POINTER_TYPE + ";)L" + DniTypes.STRUCTURE_TYPE + ";" );
        methodVisitor.visitTypeInsn( Opcodes.CHECKCAST, implType );

        methodVisitor.visitInsn( ARETURN );
    }
    
    /**
     * @return the structure record
     */
    StructureRecord getStructureRecord()
    {
        return this.structureRecord;
    }

}
